<?php
include('SimpleImage.php');

function checkUserSession() {
    if (!$_SESSION['session_user']) {
        header('Location: login.php?user='.$_SESSION['session_user']);
        exit;
    }
}

function tryLogOnUser($login, $password) {

    $login = mysql_real_escape_string($login);
    $password = mysql_real_escape_string($password);

    $result = mysql_query("select login from users where login='${login}' and password='${password}'")
        or die('Query failed: ' . mysql_error());

    $loginResult = false;
    if (mysql_fetch_array($result, MYSQL_ASSOC)) {
        $loginResult = true;
    }
    mysql_free_result($result);
    return $loginResult;

}

function changePassword($login, $password) {
    $query = sprintf("update users set password='%s' where login='%s'",
        mysql_real_escape_string($password),
        mysql_real_escape_string($login)
    );
    mysql_query($query);
}

function mysqlDateStrToArray($date) {
    $tmp = explode('-', $date);
    return array(
        "year" => $tmp[0],
        "month" => $tmp[1],
        "day" => $tmp[2],
    );
}

function webFormDateStrToArray($date) {
    $tmp = explode('.', $date);
    return array(
        "day" => $tmp[0],
        "month" => $tmp[1],
        "year" => $tmp[2],
    );
}

function arrayDateToMySqlDate($dateArray) {
    return $dateArray['year'].'-'.$dateArray['month'].'-'.$dateArray['day'];
}

function arrayDateToWebFormDate($dateArray) {
    return $dateArray['day'].'.'.$dateArray['month'].'.'.$dateArray['year'];
}

function date_parse_from_format($format, $date) {
  $dMask = array(
    'H'=>'hour',
    'i'=>'minute',
    's'=>'second',
    'y'=>'year',
    'm'=>'month',
    'd'=>'day'
  );
  $format = preg_split('//', $format, -1, PREG_SPLIT_NO_EMPTY);
  $date = preg_split('//', $date, -1, PREG_SPLIT_NO_EMPTY);
    $dt = array();
  foreach ($date as $k => $v) {
    if ($dMask[$format[$k]]) {
        $dt[$dMask[$format[$k]]] .= $v;
    }
  }
  return $dt;
}

function prepareNewsFullText($newsText) {
    $newsText = str_replace('
', '<br/>', $newsText);
    $newsText = str_replace('[b]', '<b>', $newsText);
    $newsText = str_replace('[/b]', '</b>', $newsText);
    return $newsText;
}

function saveNewsImage($newsId, $image_file_path) {
    $SITE_ROOT_FOLDER = $GLOBALS['SITE_ROOT_FOLDER'];
    if ($image_file_path) {
        $origImgPath = $GLOBALS['PATH_TO_HOME'].'upload/news/img_'.$newsId.'_orig.jpg';
//        print '\n origImgPath: '.$origImgPath;
//        print '\n image_file_path: '.$image_file_path;
        $res = move_uploaded_file($image_file_path, $origImgPath);
//        print '\n result move: '.$res;
        $image = new SimpleImage();
        $image->load($origImgPath);
        $image->resizeToWidth(300);
        $image->save($GLOBALS['PATH_TO_HOME'].'upload/news/img_'.$newsId.'.jpg');
        $image->resize(52, 52);
        $image->save($GLOBALS['PATH_TO_HOME'].'upload/news/img_'.$newsId.'_small.jpg');
    } else {
//        print 'OBLOM';
    }
}

function savePortfolioImage($portfolioId, $image_file_path) {
    $SITE_ROOT_FOLDER = $GLOBALS['SITE_ROOT_FOLDER'];
    if ($image_file_path) {
        $origImgPath = $GLOBALS['PATH_TO_HOME'].'upload/portfolios/img_'.$portfolioId.'_orig.jpg';
//        print '\n origImgPath: '.$origImgPath;
//        print '\n image_file_path: '.$image_file_path;
        $res = move_uploaded_file($image_file_path, $origImgPath);
//        print '\n result move: '.$res;
        $image = new SimpleImage();
        $image->load($origImgPath);
        if ($image->getWidth() > 650) {
            $image->resizeToWidth(650);
        }
        $image->save($GLOBALS['PATH_TO_HOME'].'upload/portfolios/img_'.$portfolioId.'.jpg');
        if ($image->getWidth() > 150) {
            $image->resizeToWidth(150);
        }
        if ($image->getHeight() > 150) {
            $image->resizeToHeight(150);
        }
        //$image->resize(52, 52);
        $image->save($GLOBALS['PATH_TO_HOME'].'upload/portfolios/img_'.$portfolioId.'_small.jpg');
    } else {
//        print 'OBLOM';
    }
}



function updateNews($news) {

    if ($news['id'] && (int)$news['id'] > 0) {

        /**
        "id"            => $_POST['id'],
        "title"         => $_POST['title'],
        "date"          => $_POST['date'],
        "short_text"    => $_POST['short_text'],
        "full_text"     => $_POST['full_text'],
         */

        $query = sprintf("update news set title='%s', news_date='%s', short_text='%s', full_text='%s', version=version+1 where id=%s",
            mysql_real_escape_string($news['title']),
            mysql_real_escape_string(arrayDateToMySqlDate($news['date'])),
            mysql_real_escape_string($news['short_text']),
            mysql_real_escape_string($news['full_text']),
            $news['id']
        );
        mysql_query($query);
        saveNewsImage($news['id'], $news['news_image']);
        //return $news;
        return getNews($news['id']);
    } else {

        $query = sprintf("insert into news (title, news_date, short_text, full_text)
                    values ('%s', '%s', '%s', '%s')",
            mysql_real_escape_string($news['title']),
            mysql_real_escape_string(arrayDateToMySqlDate($news['date'])),
            mysql_real_escape_string($news['short_text']),
            mysql_real_escape_string($news['full_text'])
        );
        mysql_query($query);
        $result = mysql_query("select last_insert_id() as newsId");
        $newsId = 0;
        if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $newsId = $row['newsId'];
        }
        saveNewsImage($newsId, $news['news_image']);
        return getNews($newsId);
    }

}

function getNews($newsId) {
    if ($newsId == 0) {
        return array();
    } else {
        $idInt = (int) $newsId;
//        $result = mysql_query("select id, title, DATE_FORMAT(news_date,'%%Y-m-%d') as news_date2, short_text, full_text from news where id=".$idInt)
        $result = mysql_query("select id, title, news_date, short_text, full_text, published, version from news where id=$idInt")
            or die('Query failed: ' . mysql_error());

        $news = array();
        if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $news = array(
                "id"            => $row['id'],
                "title"         => $row['title'],
                "date"          => mysqlDateStrToArray($row['news_date']),
                "short_text"    => $row['short_text'],
                "full_text"     => $row['full_text'],
                "published"     => $row['published'],
                "version"       => $row['version']
            );
        }
        mysql_free_result($result);
        return $news;
    }

}

function publishNews($newsId, $val) {
    mysql_query("update news set published = $val where id = $newsId");
}

function getUserNewsCount() {
    $result = mysql_query("select count(*) as news_count from news where published!=0;")
        or die('Query failed: ' . mysql_error());
    $news_count = 0;
    if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $news_count = $row['news_count'];
    }
    mysql_free_result($result);
    return $news_count;
}

function getAllNewsCount() {
    $result = mysql_query("select count(*) as news_count from news;")
        or die('Query failed: ' . mysql_error());
    $news_count = 0;
    if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $news_count = $row['news_count'];
    }
    mysql_free_result($result);
    return $news_count;
}

function getUserNews($page) {
    $limit = $GLOBALS['NEWS_PAGE_SIZE'];
    $offset = $limit * $page;
    $result = mysql_query("select id, title, news_date, short_text, full_text, published, version from news where published!=0 order by news_date desc limit $limit offset $offset;")
        or die('Query failed: ' . mysql_error());

    $news = fillNewsArray($result);
    mysql_free_result($result);
    return $news;
}

function getAllNews($page) {
    $limit = $GLOBALS['NEWS_PAGE_SIZE'];
    $offset = $limit * $page;
    $result = mysql_query("select id, title, news_date, short_text, full_text, published, version from news order by news_date desc limit $limit offset $offset;")
        or die('Query failed: ' . mysql_error());

    $news = fillNewsArray($result);
    mysql_free_result($result);
    return $news;
}

function fillNewsArray($result) {
    $news = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $id = $row['id'];
        $new = array(
            "id"            => $row['id'],
            "title"         => $row['title'],
            "date"          => mysqlDateStrToArray($row['news_date']),
            "short_text"    => $row['short_text'],
            "full_text"     => $row['full_text'],
            "published"     => $row['published'],
            "version"       => $row['version']
        );
        $news[$id] = $new;
    }
    return $news;
}

function getAllPortfolios($page) {
    $limit = $GLOBALS['PORTFOLIOS_PAGE_SIZE'];
    $offset = $limit * $page;
    $result = mysql_query("select id, title, portfolio_date, published, version from portfolios order by portfolio_date desc limit $limit offset $offset;")
        or die('Query failed: ' . mysql_error());

    $portfolios = fillPortfoliosArray($result);
    mysql_free_result($result);
    return $portfolios;
}

function getUserPortfolios($page) {
    $limit = $GLOBALS['PORTFOLIOS_PAGE_SIZE'];
    $offset = $limit * $page;
    $result = mysql_query("select id, title, portfolio_date, published, version from portfolios where published!=0 order by portfolio_date desc limit $limit offset $offset;")
        or die('Query failed: ' . mysql_error());

    $portfolios = fillPortfoliosArray($result);
    mysql_free_result($result);
    return $portfolios;
}

function getAllPortfoliosCount() {
    $result = mysql_query("select count(*) as portfolios_count from portfolios;")
        or die('Query failed: ' . mysql_error());
    $portfolios_count = 0;
    if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $portfolios_count = $row['portfolios_count'];
    }
    mysql_free_result($result);
    return $portfolios_count;
}

function getUserPortfoliosCount() {
    $result = mysql_query("select count(*) as portfolios_count from portfolios where published!=0;")
        or die('Query failed: ' . mysql_error());
    $portfolios_count = 0;
    if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $portfolios_count = $row['portfolios_count'];
    }
    mysql_free_result($result);
    return $portfolios_count;
}

function fillPortfoliosArray($result) {
    $news = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $id = $row['id'];
        $new = array(
            "id"            => $row['id'],
            "title"         => $row['title'],
            "date"          => mysqlDateStrToArray($row['portfolio_date']),
            "published"     => $row['published'],
            "version"       => $row['version']
        );
        $news[$id] = $new;
    }
    return $news;
}

function updatePortfolio($portfolio) {

    if ($portfolio['id'] && (int)$portfolio['id'] > 0) {

        $query = sprintf("update portfolios set title='%s', portfolio_date='%s', version=version+1 where id=%s",
            mysql_real_escape_string($portfolio['title']),
            mysql_real_escape_string(arrayDateToMySqlDate($portfolio['date'])),
            $portfolio['id']
        );
        mysql_query($query);
        savePortfolioImage($portfolio['id'], $portfolio['portfolio_image']);
        //return $news;
        return getPortfolio($portfolio['id']);
    } else {

        $query = sprintf("insert into portfolios (title, portfolio_date)
                    values ('%s', '%s')",
            mysql_real_escape_string($portfolio['title']),
            mysql_real_escape_string(arrayDateToMySqlDate($portfolio['date']))
        );
        mysql_query($query);
        $result = mysql_query("select last_insert_id() as portfolioId");
        $portfolioId = 0;
        if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $portfolioId = $row['portfolioId'];
        }
        savePortfolioImage($portfolioId, $portfolio['portfolio_image']);
        return getPortfolio($portfolioId);
    }

}

function getPortfolio($portfolioId) {
    if ($portfolioId == 0) {
        return array();
    } else {
        $idInt = (int) $portfolioId;
//        $result = mysql_query("select id, title, DATE_FORMAT(news_date,'%%Y-m-%d') as news_date2, short_text, full_text from news where id=".$idInt)
        $result = mysql_query("select id, title, portfolio_date, published, version from portfolios where id=$idInt")
            or die('Query failed: ' . mysql_error());

        $portfolio = array();
        if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

            $portfolio = array(
                "id"            => $row['id'],
                "title"         => $row['title'],
                "date"          => mysqlDateStrToArray($row['portfolio_date']),
                "published"     => $row['published'],
                "version"       => $row['version']
            );
        }
        mysql_free_result($result);
        return $portfolio;
    }

}

function publishPortfolio($newsId, $val) {
    mysql_query("update portfolios set published = $val where id = $newsId");
}

function getMember($memberId) {

    if ($memberId == 0) {
        return array();
    } else {
        $idInt = (int) $memberId;
        $result = mysql_query("select id, sort_order, name, address, inn, ogrn, cert_num, ext_info from members where id=".$idInt)
            or die('Query failed: ' . mysql_error());

        $member = array();
        if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $member = array(
                "id"        => $row['id'],
                "name"      => $row['name'],
                "address"   => $row['address'],
                "inn"       => $row['inn'],
                "ogrn"      => $row['ogrn'],
                "cert_num"  => $row['cert_num'],
                "ext_info"  => $row['ext_info'],
            );
        }
        mysql_free_result($result);
        return $member;
    }

}

function getMembers() {
    $result = mysql_query("select id, sort_order, name, address, inn, ogrn, cert_num from members order by sort_order;")
        or die('Query failed: ' . mysql_error());

    $members = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $id = $row['id'];
        $member = array(
            "id"        => $id,
            "name"      => $row['name'],
            "address"   => $row['address'],
            "inn"       => $row['inn'],
            "ogrn"      => $row['ogrn'],
            "cert_num"  => $row['cert_num'],
        );
        $members[$id] = $member;
    }
    mysql_free_result($result);
    return $members;
}

function mySqlOpen($mySQLserver, $mySQLuser, $mySQLpassword, $database) {
    $mylink = mysql_connect($mySQLserver, $mySQLuser, $mySQLpassword) or die('Could not connect: ' . mysql_error());
    mysql_select_db($database) or die('Could not select database');
    return $mylink;
}

function mySqlClose($mylink) {
    // Closing connection
    mysql_close($mylink);
}

?>